#define _CRT_SECURE_NO_WARNINGS 1
#include"SList.h"

void SListPrint(SListNode* plist)
{
	SListNode* cur = plist;
	while (cur)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

SListNode* BuySListNode(SLTDateType x)
{
	SListNode* newnode = (SListNode*)malloc(sizeof(SListNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}

	newnode->data = x;
	newnode->next = NULL;

	return newnode;
}

void SListPushBack(SListNode** pplist, SLTDateType x)
{
	assert(pplist);

	SListNode* newnode = BuySListNode(x);
	if (*pplist == NULL)
	{
		*pplist = newnode;
	}
	else
	{
		SListNode* tail = *pplist;
		while (tail->next)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}

void SListPushFront(SListNode** pplist, SLTDateType x)
{
	assert(pplist);
	SListNode* newnode = BuySListNode(x);
	newnode->next = *pplist;
	*pplist = newnode;
}

void SListPopBack(SListNode** pplist)
{
	assert(pplist);
	assert(*pplist);

	if ((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}
	else
	{
		SListNode* tail = *pplist;
		while (tail->next != NULL && tail->next->next != NULL)
		{
			tail = tail->next;
		}

		free(tail->next);
		tail->next = NULL;
	}
}

void SListPopFront(SListNode** pplist)
{
	assert(pplist);
	SListNode* first = *pplist;
	*pplist = first->next;
	free(first);
	first = NULL;
}

SListNode* SListFind(SListNode* plist, SLTDateType x)
{
	SListNode* cur = plist;

	while (cur)
	{
		if (cur->data == x)
			return cur;

		cur = cur->next;
	}

	return NULL;
}

void SListInsertAfter(SListNode* pos, SLTDateType x)
{
	SListNode* back = pos->next;
	if (pos == NULL)
	{
		SListPushFront(&pos, x);
	}
	else if ((pos->next) == NULL)
	{
		SListPushBack(&pos, x);
	}
	else
	{
		SListNode* newnode = BuySListNode(x);
		pos->next = newnode;
		newnode->next = back;
	}
}

void SListEraseAfter(SListNode* pos)
{
	assert(pos);
	assert(pos->next);

	SListNode* back = pos->next->next;
	pos->next = back;
}

void SLTInsert(SListNode** pphead, SListNode* pos, SLTDateType x)
{
	assert(pphead);
	assert(*pphead);

	if (*pphead == pos)
	{
		SListPushFront(pphead,x);
	}
	else
	{
		SListNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		SListNode* newnode = BuySListNode(x);
		prev->next = newnode;
		newnode->next = pos;
	}
}

void SLTErase(SListNode** pphead, SListNode* pos)
{
	assert(pphead);
	assert(*pphead);

	SListNode* prev = *pphead;
	SListNode* back = pos->next;
	while ((prev->next)!= pos)
	{
		prev = prev->next;
	}
	prev->next = back;
	free(pos);
	pos = NULL;
}

void SLTDestroy(SListNode** pphead)
{
	assert(pphead);
	assert(*pphead);

	free(*pphead);
	*pphead = NULL;
}